<template>
  <div class="app-container zzjg">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <!--                    <el-tree :data="data5" icon-class="none" :expand-on-click-node="false"-->
          <!--                        :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick">-->
          <!--                        <span class="custom-tree-node" slot-scope="{ data }">-->
          <!--                            <span style="font-size: 14px;">-->
          <!--                                <i :class="data.icon"></i>{{ data.label }}-->
          <!--                            </span>-->
          <!--                        </span>-->
          <!--                    </el-tree>-->
          <el-tree
            :data="data5"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="deptTreeRef"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template #default="scope">
              <span class="custom-tree-node">
                <span style="font-size: 14px">
                  <i :class="scope.data.icon"></i>{{ scope.data.label }}
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-row style="margin-bottom: 10px">
          <el-col :span="17" :xs="24">
            <el-input
              v-model="queryParams.searchValue"
              placeholder="组织机构名称/负责人/分管领导"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
            <el-button
              style="margin-left: 15px"
              type="primary"
              icon="Search"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-col>
          <el-col
            :span="7"
            :xs="24"
            style="
              height: 38px;
              display: flex;
              align-items: center;
              justify-content: end;
            "
          >
            <el-button
              type="primary"
              v-hasPermi="['rsgl:zzjg:add']"
              plain
              icon="Plus"
              @click="handleAdd"
              >新建组织机构</el-button
            >
            <el-button
              type="primary"
              plain
              icon="Download"
              v-hasPermi="['rsgl:zzjg:export']"
              v-loading="exportLoading"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
        </el-row>
        <!-- 列表 -->
        <el-table
          stripe
          v-loading="loading"
          :data="tableData"
          row-key="deptId"
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column
            prop="deptName"
            label="组织机构名称"
            width="200"
          ></el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span
                  :class="
                    scope.row.status == 0 ? 'node-span-green' : 'node-span-red'
                  "
                ></span>
                <span> {{ scope.row.status == 0 ? '启用' : '禁用' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="employeeNum" label="员工数量">
            <template #default="scope">
              <el-tag
                style="width: 60px; cursor: pointer"
                @click="getoEmployee(scope.row)"
              >
                {{ scope.row.employeeNum }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deptType" label="性质">
            <template #default="scope">
              {{ scope.row.deptType == 1 ? '单位' : '部门' }}
            </template>
          </el-table-column>
          <el-table-column prop="leaderName" label="负责人"></el-table-column>
          <el-table-column
            prop="chargeLeaderName"
            label="分管领导"
          ></el-table-column>
          <el-table-column label="更新时间" prop="createTime" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="100"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
          >
            <template #default="scope">
              <el-dropdown
                size="small"
                v-hasPermi="[
                  'rsgl:zzjg:update',
                  'rsgl:zzjg:set',
                  'rsgl:zzjg:remove'
                ]"
                @command="command => handleCommand(command, scope.row)"
              >
                <span class="el-dropdown-link">
                  <el-icon><DArrowRight /></el-icon>更多
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <div v-hasPermi="['rsgl:zzjg:update']">
                      <el-dropdown-item
                        command="handleUpdate"
                        icon="el-icon-edit"
                        >修改</el-dropdown-item
                      >
                    </div>
                    <div v-hasPermi="['rsgl:zzjg:set']">
                      <el-dropdown-item
                        command="handleSetState"
                        icon="el-icon-setting"
                        >设置状态</el-dropdown-item
                      >
                    </div>
                    <div v-hasPermi="['rsgl:zzjg:remove']">
                      <el-dropdown-item
                        command="handleDelete"
                        icon="el-icon-delete"
                        >删除</el-dropdown-item
                      >
                    </div>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <!--
              <el-button style="padding: 5px;" size="small" type="primary" plain icon="el-icon-edit"
                  @click="handleUpdate(scope.row)" v-hasPermi="['rsgl:zzjg:update']"
                  v-if="scope.row.parentId != 0">修改</el-button>
              <el-button style="padding: 5px;" size="small" type="primary" plain icon="el-icon-setting"
                  @click="handleSetState(scope.row)" v-hasPermi="['rsgl:zzjg:set']">设置状态</el-button>
              <el-button style="padding: 5px;" type="danger" plain v-if="scope.row.parentId != 0"
                  size="small" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['rsgl:zzjg:remove']">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <el-form
        v-if="title != '设置状态'"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="组织机构名称:" prop="deptName">
          <el-input
            v-model="form.deptName"
            placeholder="请输入组织机构名称"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item label="组织机构性质:" prop="deptType">
          <el-select
            v-model="form.deptType"
            placeholder="请选择组织机构性质"
            style="width: 100%"
          >
            <el-option label="单位" value="1"></el-option>
            <el-option label="部门" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级机构:" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="sjjgOptions"
            class="w-full"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            placeholder="选择上级机构"
            value-key="id"
            filterable
            check-strictly
          />
        </el-form-item>
        <el-form-item label="分管领导:">
          <!--          <treeselect-->
          <!--            v-model="form.chargeLeader"-->
          <!--            :options="deptOptions"-->
          <!--            :normalizer="normalizer"-->
          <!--            placeholder="请选择分管领导"-->
          <!--            :disable-branch-nodes="true"-->
          <!--          />-->
          <el-tree-select
            v-model="form.chargeLeader"
            :data="deptOptions"
            class="w-full"
            multiple
            :props="{
              value: 'id',
              label: 'label',
              children: 'children',
              disabled: 'disabled'
            }"
            placeholder="请选择分管领导"
            value-key="id"
            filterable
          />
        </el-form-item>
        <el-form-item label="负责人:">
          <!--         <treeselect-->
          <!--            v-model="form.leader"-->
          <!--            :options="deptOptions"-->
          <!--            :normalizer="normalizer"-->
          <!--            placeholder="请选择负责人"-->
          <!--            :disable-branch-nodes="true"-->
          <!--          />-->
          <el-tree-select
            v-model="form.leader"
            :data="deptOptions"
            class="w-full"
            :props="{
              value: 'id',
              label: 'label',
              children: 'children',
              disabled: 'disabled'
            }"
            placeholder="请选择负责人"
            value-key="id"
            filterable
          />
        </el-form-item>
        <el-form-item label="组织机构描述:">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <el-form
        v-else
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="组织机构:">
          <el-input v-model="form.deptName" disabled />
        </el-form-item>
        <el-form-item label="选择状态:">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm" v-loading="loadingBtm"
            >保 存</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Zzjg">
import {
  listDept,
  employeeTreeselect,
  treeselect,
  getDept,
  delDept,
  addDept,
  updateDept,
  setStatus
} from '@/api/rsgl/zzjg'
import { getCurrentInstance, nextTick, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
const { proxy } = getCurrentInstance()
const data = reactive({
  // 表格树数据
  tableData: [],
  // 遮罩层
  loading: true,
  // 导出遮罩层
  exportLoading: false,
  // 选中数组
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 用户表格数据
  userList: null,
  // 弹出层标题
  title: '',
  // 部门树选项
  deptOptions: [],
  sjjgOptions: undefined,
  data5: [],
  // 是否显示弹出层
  open: false,
  // 表单参数
  form: {},
  // 查询参数
  queryParams: {
    searchValue: undefined,
    deptId: undefined
  },

  // 表单校验
  rules: {
    deptName: [
      { required: true, message: '组织机构名称不能为空', trigger: 'blur' }
    ],
    deptType: [
      { required: true, message: '组织机构性质不能为空', trigger: 'blur' }
    ],
    parentId: [{ required: true, message: '上级机构不能为空', trigger: 'blur' }]
  }
})
const {
  deptOptions,
  sjjgOptions,
  data5,
  queryParams,
  form,
  open,
  tableData,
  loading,
  exportLoading,
  single,
  multiple,
  showSearch,
  total,
  userList,
  title,
  rules
} = toRefs(data)
const formRef = ref()
const loadingBtm = ref(false)
const router = useRouter()
//跳转员工档案
function getoEmployee(row) {
  console.log('deptId===', row.deptId)
  router.push({
    path: '/rsgl/rs/rsglYgda',
    query: { deptId: row.deptId }
  })
}

/** 转换部门数据结构 */
function normalizer(data) {
  if (data) {
    data.map(item => {
      if (item.children && item.children.length > 0) {
        normalizer(item.children)
      } else {
        item.disabled = !item.children && item.selectFlag == '0' ? true : false
      }
    })
  }
  return data
}
/** 查询部门列表 */
function getList() {
  loading.value = true
  listDept(queryParams.value).then(response => {
    tableData.value = proxy.handleTree(response.data, 'deptId')
    loading.value = false
  })
}

/** 查询部门下拉树结构 */
function getTreeselect() {
  treeselect({ deptType: 1 }).then(response => {
    data5.value = readNodes(response.data)
    console.log(data5)
  })
}

// 设置树形图标
function readNodes(nodes = []) {
  for (let item of nodes) {
    let icon =
      item.id == 100
        ? 'iconfontone tt-iconzuzhijiagou1'
        : 'iconfontone tt-iconzuzhijiagou'
    item.icon = icon
    if (item.children && item.children.length) readNodes(item.children)
  }
  return nodes
}

// 筛选节点
function filterNode(value, data) {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

// 节点单击事件
function handleNodeClick(data) {
  queryParams.value.deptId = data.id
  getList()
}

// 取消按钮
function cancel() {
  open.value = false
}

// 表单重置
function reset() {
  form.value = {
    deptName: undefined,
    deptType: undefined,
    parentId: undefined,
    remark: undefined,
    chargeLeader: undefined,
    leader: undefined
  }
  proxy.resetForm('form')
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    searchValue: undefined,
    deptId: undefined
  }
  handleQuery()
}

/** 新增按钮操作 */
async function handleAdd() {
  reset()
  let response = await employeeTreeselect({
    deptId: queryParams.value.deptId || null
  })

  deptOptions.value = normalizer(response.data)
  let res = await treeselect({ deptId: queryParams.value.deptId || null })
  sjjgOptions.value = res.data
  open.value = true
  title.value = '新建组织架构用户'
}

// 更多操作触发
function handleCommand(command, row) {
  switch (command) {
    case 'handleUpdate':
      handleUpdate(row)
      break
    case 'handleSetState':
      handleSetState(row)
      break
    case 'handleDelete':
      handleDelete(row)
      break
    default:
      break
  }
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  let response = await employeeTreeselect({
    deptId: queryParams.value.deptId || null
  })
  // deptOptions.value = response.data
  deptOptions.value = normalizer(response.data)

  treeselect({ deptId: queryParams.value.deptId || null }).then(response => {
    sjjgOptions.value = response.data
    getDept(row.deptId).then(res => {
      res.data.chargeLeader =
        res.data.chargeLeader == null || res.data.chargeLeader == ''
          ? ''
          : res.data.chargeLeader.split(',')
      const data = res.data
      Object.keys(data).forEach(key => {
        if (key == 'leader') {
          if (data[key] != null) {
            data[key] = data[key] + ''
          } else {
            data[key] = undefined
          }
        }
      })
      form.value = data

      nextTick(() => {
        open.value = true
        title.value = '修改组织架构'
      })
    })
  })
}

// 设置状态
function handleSetState(row) {
  let deptIds = []
  deptIds.push(row.deptId)
  form.value = {
    deptName: row.deptName,
    deptIds,
    status: parseInt(row.status)
  }
  open.value = true
  title.value = '设置状态'
}

/** 提交按钮 */
function submitForm() {
  console.log('form===', form.value)

  proxy.$refs['formRef'].validate(valid => {
    if (valid) {
      loadingBtm.value = true
      if (form.value.deptIds != undefined) {
        setStatus(form.value)
          .then(res => {
            if (res.code == 200) {
              getList()

              proxy.$modal.msgSuccess('设置状态成功')
            } else {
              proxy.$modal.msgError(res.msg)
            }
            open.value = false
          })
          .finally(() => {
            loadingBtm.value = false
          })
      } else if (form.value.deptId != undefined) {
        form.value.chargeLeader =
          form.value.chargeLeader.length > 0
            ? form.value.chargeLeader.join(',')
            : ''
        updateDept(form.value)
          .then(res => {
            if (res.code == 200) {
              getList()

              proxy.$modal.msgSuccess('修改成功')
            } else {
              proxy.$modal.msgError(res.msg)
            }
            open.value = false
          })
          .finally(() => {
            loadingBtm.value = false
          })
      } else {
        form.value.chargeLeader =
          form.value.chargeLeader.length > 0
            ? form.value.chargeLeader.join(',')
            : ''
        addDept(form.value)
          .then(res => {
            if (res.code == 200) {
              getList()

              proxy.$modal.msgSuccess('新增成功')
            } else {
              proxy.$modal.msgError(res.msg)
            }
            open.value = false
          })
          .finally(() => {
            loadingBtm.value = false
          })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm('是否确定删除该组织机构？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(function () {
      return delDept(row.deptId)
    })
    .then(res => {
      if (res.code == 200) {
        getList()
        proxy.$modal.msgSuccess('删除成功')
      } else {
        proxy.$modal.msgError(res.msg)
      }
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  ElMessageBox.confirm('是否确认导出相关人员记录？', '操作确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    icon: 'QuestionFilled',
    type: 'warning'
  }).then(() => {
    proxy.downLoadByUrl('/system/dept/export', queryParams.value)
  })
}

getList()
getTreeselect()
</script>

<style lang="scss" scoped>
.expanded.el-tree-node__expand-icon.none {
  display: none;
}

.node-span-red {
  font-size: 14px;
  color: red;

  &::before {
    content: '';
    display: block;
    width: 5px;
    height: 5px;
    background: red;
    border-radius: 50%;
    margin-right: 6px;
  }
}

.node-span-green {
  font-size: 14px;
  color: green;

  &::before {
    content: '';
    display: block;
    width: 5px;
    height: 5px;
    background: green;
    border-radius: 50%;
    margin-right: 6px;
  }
}
</style>
